package com.dminvoicemanager.itinerary;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.DM_InvoiceDetails;
import com.dminvoicemanager.DM_InvoiceMainActivity;
import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_List_Expand_Helper;
import com.dminvoicemanager.DM_Settings;
import com.dminvoicemanager.DM_Stock_UnLoading;
import com.dminvoicemanager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DM_Itinerary_Report_Details extends Activity {
	private static final String TAG = null;
	SQLiteDatabase mydb;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String YEARS_LIST = "FYearsList";
	private String MONTH_LIST = "FMonthList";
	// Itinerary Report
	private String ITINERARY_HEAD = "FItenrHed";
	private String ITINERARY_DETAILS = "FItenrDet";
	private String ITINERARY_DETTAIL_DET = "FIteDetDet";

	private String SALES_REP_ROUTE = "fRoute";
	private String SALES_REP_ROUTEDET = "fRouteDet";
	private String ITEM_DEBTOR = "fDebtor";

	LinearLayout dmselectitineryroute, dmselectitineryRetailer,
			dminvoiceitemsdetails, invheaderbuttons;

	EditText etitineraryrouteval, etitinoofoutval, etitischedulecallval,
			etitirdtargetval, etitiremarkval, etitiretailerval;

	Button dmselectineraryroute, dmselectitiretailer, btninvupdateitem,
			btnitideleterecord, btnitiupdatedetails;

	String TagId, Iti_Identifire, Iti_TxnDate, itineraryRoutecode,
			itineraryRoutename, currentRefNo = "0", receiptinvcuscode,
			receiptinvcusname, receiptinvcusdiscount, currentUserStLoad,
			currentUserPrefixLoad, currentUserLocation, currentUserAreaCode,
			currentTxnDate, Itifitenrdet_id, Itifitedetdet_id,stlAgentPrefixType,stlAgentDealCode,StlTransTypePrefix;

	int countOutlet = 0, SchCallCountList, SchCallCountListSum,
			SchCallCountDelList, TAGRECCHK = 0, DELRECTAG = 0, RESETTAG = 0,
			CHKRETAILER = 0;
	AlertDialog StockLoadingAlert = null;
	final private static int DIALOG_CHK_RECORDS = 1;

	// Back to Itinary Main Screen
	public void btnExitScreen(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_Itinerary_Report_Main.class);
		myIntent.putExtra("TAGID", "400");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	// Back to main screen
	public void btnItemsListBack(View view) {
		dmselectitineryRetailer.setVisibility(view.GONE);
		dmselectitineryroute.setVisibility(view.GONE);
		dminvoiceitemsdetails.setVisibility(view.VISIBLE);
		dminvoiceitemsdetails.setVisibility(view.VISIBLE);
		invheaderbuttons.setVisibility(view.VISIBLE);
	}

	public void btnConfirmAccept(View view) {
		RESETTAG = 200;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			mydb.delete(ITINERARY_DETAILS, "RefNo ='" + currentRefNo + "'",
					null);

			mydb.delete(ITINERARY_DETTAIL_DET, "RefNoDet ='" + currentRefNo
					+ "'", null);

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		displayItineraryDetailsList();
		clearItianararyDetails();

		mydb.close();
	}

	public void btnCancelAccept(View view) {
		StockLoadingAlert.dismiss();
	}

	// Print Route Description
	public void AddLocationDetails(View view) {
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		String[] accountdetail = SetTransactionDesc.split("/");
		itineraryRoutecode = accountdetail[0]; // invcuscode
		itineraryRoutename = accountdetail[1]; // invcusname
		String itineraryRoutetarget = accountdetail[2]; // invcusname
		// checkNoOfOutlet();
		populateRouteRetailersList(); // Itinarary Route List
		String countOutletStr = Integer.toString(countOutlet);
		etitineraryrouteval.setText(itineraryRoutename);
		etitinoofoutval.setText(countOutletStr);
		etitirdtargetval.setText(itineraryRoutetarget);

		dmselectitineryRetailer.setVisibility(view.GONE);
		dmselectitineryroute.setVisibility(view.GONE);
		dminvoiceitemsdetails.setVisibility(view.VISIBLE);
		dminvoiceitemsdetails.setVisibility(view.VISIBLE);
		invheaderbuttons.setVisibility(view.VISIBLE);
	}

	// Print Customer Description
	public void AddCustomerDetails(View view) {
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		String[] accountdetail = SetTransactionDesc.split("/");
		receiptinvcuscode = accountdetail[0]; // invcuscode
		receiptinvcusname = accountdetail[1]; // invcusname
		receiptinvcusdiscount = accountdetail[2]; // invcusdiscount

		checkPreRetailer();

		if (CHKRETAILER == 404) {
			btninvupdateitem.setEnabled(true);
			etitiretailerval.setText(receiptinvcusname);
			dmselectitineryRetailer.setVisibility(view.GONE);
			dmselectitineryroute.setVisibility(view.GONE);
			dminvoiceitemsdetails.setVisibility(view.VISIBLE);
			dminvoiceitemsdetails.setVisibility(view.VISIBLE);
			invheaderbuttons.setVisibility(view.VISIBLE);
		}
	}

	private void checkPreRetailer() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkPreRetailer = null;
		try {
			chkPreRetailer = mydb.query(ITINERARY_DETTAIL_DET, null,
					"RefNoDet='" + currentRefNo + "' AND DebCode= '"
							+ receiptinvcuscode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (chkPreRetailer != null) {
			if (chkPreRetailer.getCount() > 0) {
				while (chkPreRetailer.moveToNext()) {
					CHKRETAILER = 0;
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Itinerary_Report_Details.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT NEW RETAILER");
					// Setting Dialog Message
					alertDialog
							.setMessage("Selected Retailer Already Scheduled...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					return;
				}
			} else {
				CHKRETAILER = 404;
			}
		} else {
			CHKRETAILER = 404;
		}
		chkPreRetailer.close();
		mydb.close();
	}

	// Populate Retailers from the selected route
	private void populateRouteRetailersList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewItineryRetailerList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoicecustommer, R.id.invcustomername };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curChkRetail = null;
		try {
			String queryRetail = "SELECT RD.DebCode,RD.RouteCode,FD.DebCode,FD.DebName,FD.OutDis FROM fRouteDet RD,fDebtor FD Where RD.DebCode = FD.DebCode AND RD.RouteCode = '"
					+ itineraryRoutecode + "'";
			curChkRetail = mydb.rawQuery(queryRetail, null);
		} catch (Exception e) {
		}
		if (curChkRetail != null) {
			if (curChkRetail.getCount() > 0) {
				while (curChkRetail.moveToNext()) {
					// Retailers counter
					countOutlet = countOutlet + 1;
					String customercode = curChkRetail.getString(2);
					String customername = curChkRetail.getString(3);
					String customerdiscount = curChkRetail.getString(4);
					String columncusdet = customercode + "/" + customername
							+ "/" + customerdiscount;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", columncusdet);
					maptrdes.put("coldes_2", customername);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_customer_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curChkRetail.close();
		mydb.close();
	}

	public void ShowItinararyDetails(View view) {
		Button desIti = (Button) view;
		String SetItinararyDesc = desIti.getText().toString();
		String[] itinararydetail = SetItinararyDesc.split("/");

		Itifitenrdet_id = itinararydetail[0];
		String ItiNoOutlet = itinararydetail[1];
		String ItiNoShcuCal = itinararydetail[2];
		String ItiRDTarget = itinararydetail[3];
		String ItiRemarks = itinararydetail[4];
		Itifitedetdet_id = itinararydetail[5];
		String ItiDebCode = itinararydetail[6];
		String ItiDebName = itinararydetail[7];
		String ItiRouteName = itinararydetail[8];

		btninvupdateitem.setEnabled(false);
		etitiretailerval.setText(ItiDebName);

	}

	// ============Main Class Methods=============
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_itinerary_report_details);
		// myIntent.putExtra("TAGID", IDENTIFIRE+"/"+selectedTxnDate);
		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");
		String[] itinararydetailrec = TagId.split("=");
		Iti_Identifire = itinararydetailrec[0];
		Iti_TxnDate = itinararydetailrec[1];

		Log.v(TAG, "Iti_Identifire :" + Iti_Identifire);
		Log.v(TAG, "Iti_TxnDate    :" + Iti_TxnDate);

		dmselectitineryroute = (LinearLayout) findViewById(R.id.dmselectitineryroute);
		dmselectitineryRetailer = (LinearLayout) findViewById(R.id.dmselectitineryRetailer);
		dminvoiceitemsdetails = (LinearLayout) findViewById(R.id.dminvoiceitemsdetails);
		dminvoiceitemsdetails = (LinearLayout) findViewById(R.id.dminvoiceitemsdetails);
		invheaderbuttons = (LinearLayout) findViewById(R.id.invheaderbuttons);

		dmselectineraryroute = (Button) findViewById(R.id.dmselectineraryroute);
		dmselectitiretailer = (Button) findViewById(R.id.dmselectitiretailer);
		btninvupdateitem = (Button) findViewById(R.id.btninvupdateitem);
		btnitideleterecord = (Button) findViewById(R.id.btnitideleterecord);
		btnitiupdatedetails = (Button) findViewById(R.id.btnitiupdatedetails);

		etitineraryrouteval = (EditText) findViewById(R.id.etitineraryrouteval);
		etitinoofoutval = (EditText) findViewById(R.id.etitinoofoutval);
		etitischedulecallval = (EditText) findViewById(R.id.etitischedulecallval);
		etitirdtargetval = (EditText) findViewById(R.id.etitirdtargetval);
		etitiremarkval = (EditText) findViewById(R.id.etitiremarkval);
		etitiretailerval = (EditText) findViewById(R.id.etitiretailerval);

		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Itinerary Entry Details");

		currentUserStLoadChk();
		stLoadingAgentPrefix();
		stLoadingTransType();// Check Current Trans Type
		
		currentItinararyRefDet();
		populateRouteList(); // Itinarary Route List

		displayItineraryDetailsSummary();
		displayItineraryDetailsList();
		dmselectineraryroute.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// check if current route have records
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor chkDetails;
				try {

					String query = "SELECT ID.fitenrdet_id,ID.RouteCode,ID.RefNo,ID.NoOutlet,ID.NoShcuCal,ID.RDTarget,ID.Remarks,ID.RouteName,IDD.fitedetdet_id,IDD.RouteCode,IDD.RefNoDet,IDD.DebCode,IDD.DebName from FItenrDet ID,FIteDetDet IDD Where ID.RefNo = IDD.RefNoDet AND ID.RefNo='"
							+ currentRefNo + "' group by IDD.DebCode";
					chkDetails = mydb.rawQuery(query, null);

					if (chkDetails != null) {
						if (chkDetails.getCount() > 0) {
							while (chkDetails.moveToNext()) {
								TAGRECCHK = 200;
								try {
									showDialog(DIALOG_CHK_RECORDS);
								} catch (Exception ex) {
									ex.printStackTrace();
								}
							}
						} else {
							countOutlet = 0;
							dmselectitineryroute.setVisibility(view.VISIBLE);
							dmselectitineryRetailer.setVisibility(view.GONE);
							dminvoiceitemsdetails.setVisibility(view.GONE);
							dminvoiceitemsdetails.setVisibility(view.GONE);
							invheaderbuttons.setVisibility(view.GONE);
						}
					}

				} catch (Exception e) {

				}

			}
		});

		// ********Display Customer List*********
		dmselectitiretailer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (etitineraryrouteval.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Itinerary_Report_Details.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT ROUTE");
					// Setting Dialog Message
					alertDialog
							.setMessage("Select Valid Route From The List...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					return;
				} else {
					dmselectitineryRetailer.setVisibility(view.VISIBLE);
					dmselectitineryroute.setVisibility(view.GONE);
					dminvoiceitemsdetails.setVisibility(view.GONE);
					dminvoiceitemsdetails.setVisibility(view.GONE);
					invheaderbuttons.setVisibility(view.GONE);
				}
			}
		});

		// Add retailer for shedule call
		btninvupdateitem.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				if (etitiretailerval.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Itinerary_Report_Details.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT RETAILER");
					// Setting Dialog Message
					alertDialog
							.setMessage("Select Valid Retailer From The List...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					return;
				} else {
					// *****Check Available Ref for the current Month/ Date
					// /Identifire
					SchCallCountList = SchCallCountList + 1;
					Cursor chkActiveRefAvailable = null;
					try {
						// Iti_Identifire/Iti_TxnDate
						String queryChkRef = "SELECT ItiRefIdentifire from FItenrHed Where ItiRefIdentifire = '"
								+ Iti_Identifire + "'";
						chkActiveRefAvailable = mydb
								.rawQuery(queryChkRef, null);
					} catch (Exception e) {
						Log.v(TAG, "Exception :" + e);
					}

					if (chkActiveRefAvailable != null) {
						if (chkActiveRefAvailable.getCount() > 0) {
							while (chkActiveRefAvailable.moveToNext()) {
								// *****Current Record Having Ref No
								saveRecItiDetails(); // Save to FItenrDet
								saveRecItiDetDetails(); // Save to FIteDetDet
							}
						} else {
							// Need to Generate New Ref No Before Save Record
							saveItineraryTransaction();
						}
					}
				}
			}
		});

		// delete current retailer record from the list
		btnitideleterecord.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				DELRECTAG = 404;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				try {
					mydb.delete(ITINERARY_DETAILS, "fitenrdet_id ='"
							+ Itifitenrdet_id + "'", null);

					mydb.delete(ITINERARY_DETTAIL_DET, "fitedetdet_id ='"
							+ Itifitedetdet_id + "'", null);

					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Itinerary_Report_Details.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("DELETE");
					// Setting Dialog Message
					alertDialog.setMessage("Record Deleted Successfully");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();

								}
							});
					displayItineraryDetailsList();
					clearItianararyDetails();
					/*
					 * showCurrentInvoiceItemsList(); updateInvoiceValue();
					 */

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				mydb.close();
			}
		});

		// Update Main details
		btnitiupdatedetails.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				try {
					ContentValues newrecItiDet = new ContentValues();
					newrecItiDet.put("NoShcuCal", etitischedulecallval
							.getText().toString());
					newrecItiDet.put("ActiveRec", "1");
					mydb.update(ITINERARY_DETAILS, newrecItiDet,
							"ActiveRec ='0'", null);
				} catch (Exception e) {

				}
				try {
					ContentValues newrecItiDetDet = new ContentValues();
					newrecItiDetDet.put("ActiveRecDet", "1");
					mydb.update(ITINERARY_DETTAIL_DET, newrecItiDetDet,
							"RefNoDet ='" + currentRefNo + "'", null);

				} catch (Exception e) {

				}
				Intent myIntent = new Intent(view.getContext(),
						DM_Itinerary_Report_Main.class);
				myIntent.putExtra("TAGID", "SALES");
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
				// updateItinaryHead();
				mydb.close();
			}
		});
	}

	// Check Current Trans Type
		private void stLoadingTransType() {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor selectTransType = null;

			try {
				selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
						null, null, null, null);
			} catch (Exception e) {
			}
			if (selectTransType != null) {
				if (selectTransType.getCount() > 0) {
					while (selectTransType.moveToNext()) {
						String cSettingsCode = selectTransType.getString(1);
						String cCharValue = selectTransType.getString(4);
						if (cSettingsCode.equals("ITNARY")) {
							StlTransTypePrefix = cCharValue.trim();
						}
					}
				}
			}
			selectTransType.close();
			mydb.close();
		}


	protected void saveItineraryTransaction() {
		// TODO Auto-generated method stub
		
	}

	private void stLoadingAgentPrefix() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					stlAgentPrefixType = selectAgentPreType.getString(18);
					stlAgentDealCode = selectAgentPreType.getString(19);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	private void displayItineraryDetailsSummary() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectItiSum = null;
		try {
			String query = "SELECT RouteCode,RouteName,NoOutlet,NoShcuCal,RDTarget,Remarks from FItenrDet Where ActiveRecIdentifire = '"
					+ Iti_Identifire + "' AND TxnDate = '"+ Iti_TxnDate +"'";
			selectItiSum = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (selectItiSum != null) {
			if (selectItiSum.getCount() > 0) {
				while (selectItiSum.moveToNext()) {
					itineraryRoutecode = selectItiSum.getString(0);
					itineraryRoutename = selectItiSum.getString(1);
					String strNoOutlet = selectItiSum.getString(2);
					String strNoShcuCal = selectItiSum.getString(3);
					String RDTarget = selectItiSum.getString(4);
					String strRemarks = selectItiSum.getString(5);
					etitineraryrouteval.setText(itineraryRoutename);
					etitinoofoutval.setText(strNoOutlet);
					// etitischedulecallval.setText(strNoShcuCal);
					etitirdtargetval.setText(RDTarget);
					etitiremarkval.setText(strRemarks);
				}
			}
		}
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current User
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {
					currentUserStLoad = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					currentUserLocation = selectCurrentuserLoad.getString(3);
					currentUserAreaCode = selectCurrentuserLoad.getString(9);
				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	private void currentItinararyRefDet() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentItinararyLoad = null;
		try {
			selectCurrentItinararyLoad = mydb.query(ITINERARY_HEAD, null,
					"ItinaryUser='" + currentUserStLoad
							+ "' AND ItenrHedActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (selectCurrentItinararyLoad != null) {
			if (selectCurrentItinararyLoad.getCount() > 0) {
				while (selectCurrentItinararyLoad.moveToNext()) {
					currentRefNo = selectCurrentItinararyLoad.getString(1);
					currentTxnDate = selectCurrentItinararyLoad.getString(12);

					Log.v(TAG, "Current Ref :" + currentRefNo);
				}
			}
		}
	}

	protected void saveRecItiDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkActiveItiDetAvailable = null;
		try {
			// Iti_Identifire/Iti_TxnDate
			String queryChkRef = "SELECT TxnDate from FItenrDet Where TxnDate = '"
					+ Iti_TxnDate + "'";
			chkActiveItiDetAvailable = mydb.rawQuery(queryChkRef, null);
		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}

		if (chkActiveItiDetAvailable != null) {
			if (chkActiveItiDetAvailable.getCount() > 0) {
				while (chkActiveItiDetAvailable.moveToNext()) {
					Log.v(TAG, "FItenrDet Already Excist For the Date");
				}
			} else {
				try {
					Log.v(TAG, "ITINERARY_DETAILS SAVE");
					ContentValues newItiDetails = new ContentValues();
					newItiDetails.put("RefNo", currentRefNo);
					newItiDetails.put("TxnDate", Iti_TxnDate);
					newItiDetails.put("RouteCode", itineraryRoutecode);
					newItiDetails.put("NoOutlet", etitinoofoutval.getText()
							.toString());
					newItiDetails.put("NoShcuCal", etitischedulecallval
							.getText().toString());
					newItiDetails.put("RDTarget", etitirdtargetval.getText()
							.toString());
					newItiDetails.put("Remarks", etitiremarkval.getText()
							.toString());
					newItiDetails.put("RouteName", etitineraryrouteval
							.getText().toString().trim());
					newItiDetails.put("ActiveRec", "0");
					newItiDetails.put("ActiveRecIdentifire", Iti_Identifire);
					mydb.insert(ITINERARY_DETAILS, null, newItiDetails);
				} catch (Exception e) {
					Log.v(TAG, "Exception :" + e);
				}
			}
		}
		mydb.close();
	}

	protected void saveRecItiDetDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			Log.v(TAG, "ITINERARY_DETTAIL_DET SAVE");
			ContentValues newItiDetDetails = new ContentValues();
			newItiDetDetails.put("RefNoDet", currentRefNo);
			newItiDetDetails.put("TxnDate", Iti_TxnDate);
			newItiDetDetails.put("RouteCode", itineraryRoutecode);
			newItiDetDetails.put("DebCode", receiptinvcuscode);
			newItiDetDetails.put("DebName", etitiretailerval.getText()
					.toString().trim());
			newItiDetDetails.put("ActiveRecDet", "0");

			mydb.insert(ITINERARY_DETTAIL_DET, null, newItiDetDetails);
		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}
		displayItineraryDetailsList();
		mydb.close();
	}

	// Display Added Itinarary Summary Details
	protected void displayItineraryDetailsList() {
		// TODO Auto-generated method stub
		Log.v(TAG, "Display List Ref :" + currentRefNo);
		ListView lvtypedes = (ListView) findViewById(R.id.dmitidetailslist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3" };
		int[] totrdes = new int[] { R.id.itiretailcode,
				R.id.itiretailcodedetail, R.id.btnitiretailcodedetail };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor listCurrentItiLoadDet = null;
		try {

			String query = "SELECT ID.fitenrdet_id,ID.RouteCode,ID.RefNo,ID.NoOutlet,ID.NoShcuCal,ID.RDTarget,ID.Remarks,ID.RouteName,IDD.fitedetdet_id,IDD.RouteCode,IDD.RefNoDet,IDD.DebCode,IDD.DebName from FItenrDet ID,FIteDetDet IDD Where ID.RefNo = IDD.RefNoDet AND ID.RefNo='"
					+ currentRefNo
					+ "' AND ID.TxnDate = '"
					+ Iti_TxnDate
					+ "' group by IDD.DebCode";
			listCurrentItiLoadDet = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}

		if (listCurrentItiLoadDet != null) {
			if (listCurrentItiLoadDet.getCount() > 0) {
				SchCallCountListSum = 0;
				while (listCurrentItiLoadDet.moveToNext()) {
					SchCallCountListSum = SchCallCountListSum + 1;
					String Itifitenrdet_id = listCurrentItiLoadDet.getString(0);
					String ItiNoOutlet = listCurrentItiLoadDet.getString(3);
					String ItiNoShcuCal = listCurrentItiLoadDet.getString(4);
					String ItiRDTarget = listCurrentItiLoadDet.getString(5);
					String ItiRemarks = listCurrentItiLoadDet.getString(6);
					String ItiRouteName = listCurrentItiLoadDet.getString(7);
					String Itifitedetdet_id = listCurrentItiLoadDet
							.getString(8);
					String ItiDebCode = listCurrentItiLoadDet.getString(11);
					String ItiDebName = listCurrentItiLoadDet.getString(12);
					Log.v(TAG, "ItiDebCode :" + ItiDebCode);
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", ItiDebCode);
					maptrdes.put("coldes_2", ItiDebName);
					maptrdes.put("coldes_3", Itifitenrdet_id + "/"
							+ ItiNoOutlet + "/" + ItiNoShcuCal + "/"
							+ ItiRDTarget + "/" + ItiRemarks + "/"
							+ Itifitedetdet_id + "/" + ItiDebCode + "/"
							+ ItiDebName + "/" + ItiRouteName);

					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_itinarary_details_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			} else {
				if (RESETTAG == 200 || DELRECTAG == 404) {
					StockLoadingAlert.dismiss();
					Intent myIntent = new Intent(this,
							DM_Itinerary_Report_Details.class);
					myIntent.putExtra("TAGID", itineraryRoutecode + "/"
							+ itineraryRoutename);
					myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivityForResult(myIntent, 0);
					DELRECTAG = 0;
					finish();
					return;
				}

				// Log.v(TAG, "Out Loop");
			}
		}
		String StrSchCallCountListSum = Integer.toString(SchCallCountListSum);
		etitischedulecallval.setText(StrSchCallCountListSum);
		listCurrentItiLoadDet.close();
		mydb.close();
		clearItianararyDetails();
	}

	private void clearItianararyDetails() {
		// TODO Auto-generated method stub
		etitiretailerval.setText("");
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Itinarary Route List
	private void populateRouteList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewItineryRouteList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invstloclocationname,
				R.id.invstloclocationdetails };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			allrowtypedes = mydb.query(SALES_REP_ROUTE, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String RouteCode = allrowtypedes.getString(2);
					String RouteName = allrowtypedes.getString(3);
					String RDTarget = allrowtypedes.getString(12);
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", RouteName);
					maptrdes.put("coldes_2", RouteCode + "/" + RouteName + "/"
							+ RDTarget);
					fillMapstrdes.add(maptrdes);
				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_stock_locations_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
				DM_List_Expand_Helper.getListViewSize(lvtypedes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	// **********Handling Dialog Box Functions*******************
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_CHK_RECORDS:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_chk_confirmation, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Change Current Route");
			dialogbuilder.setView(dialogview);
			StockLoadingAlert = dialogbuilder.create();
			break;
		}

		return StockLoadingAlert;

	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
